package com.eduagent.xwqeduagent.api.OneSentenceReprint.api;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import lombok.Data;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 声音复刻鉴权服务
 */
@Service
public class AuthService {

    @Value("${xfyun.appid}")
    private String APPID;

    @Value("${xfyun.apikey}")
    private String APIKEY;

    @Value("${xfyun.apisecret}")
    private String APISECRET;

    private static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    private static final Gson GSON = new Gson();
    private static final String TOKEN_URL = "http://avatar-hci.xfyousheng.com/aiauth/v1/token";

    /**
     * 获取鉴权token
     * @return 返回获取到的鉴权token
     * @throws Exception 请求异常时抛出
     */
    public String getToken() throws Exception {
        // 创建请求体
        Map<String, Object> requestJson = new HashMap<>();
        Map<String, Object> base = new HashMap<>();
        base.put("appid", APPID);
        base.put("version", "v1");
        String timestamp = System.currentTimeMillis() + "";
        base.put("timestamp", timestamp);
        requestJson.put("base", base);
        requestJson.put("model", "remote");
        String body = GSON.toJson(requestJson);
        
        // 设置请求类型
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody httpBody = RequestBody.create(JSON, body);

        // 生成Authorization签名
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(to32LowerCase((APIKEY + timestamp).getBytes()));
        stringBuilder.append(body);
        String authorization = to32LowerCase(stringBuilder.toString().getBytes());
        
        // 构建请求
        Request request = new Request.Builder()
                .url(TOKEN_URL)
                .method("POST", httpBody)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", authorization)
                .build();
        
        // 发送请求并获取响应
        Response response = HTTP_CLIENT.newCall(request).execute();
        TokenResponse tokenResponse = GSON.fromJson(response.body().string(), TokenResponse.class);
        
        // 检查响应状态
        if (!"000000".equals(tokenResponse.getRetcode())) {
            throw new RuntimeException("获取token失败：" + tokenResponse.getRetcode());
        }
        
        return tokenResponse.getAccesstoken();
    }
    
    /**
     * 生成32位小写MD5值
     * @param bytes 需要计算MD5的字节数组
     * @return 返回32位小写MD5值
     */
    public static String to32LowerCase(byte[] bytes) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(bytes);
            byte[] digest = md.digest();
            return String.format("%032x", new BigInteger(1, digest));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5算法不可用", e);
        }
    }

    /**
     * Token响应类
     */
    @Data
    public static class TokenResponse {
        private String expiresin;
        private String retcode;
        private String accesstoken;
    }
} 